package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.pojo.entity.AppUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.mapper.AppUserMapper;
import com.ruoyi.system.service.AppUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * ClassName：AppUserServiceImpl
 * Package：com.ruoyi.system.service.impl
 * Description：
 *
 * @Author：fpy
 * @Create：2025/5/12 - 11:10
 * @Version：v1.0
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {
    @Resource
    private AppUserMapper appUserMapper;

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public AppUser selectOrInsertAppUserByUserName(String userName) {
        AppUser appUser = appUserMapper.selectOne(
                Wrappers.<AppUser>lambdaQuery()
                        .eq(AppUser::getUserName, userName)
                        .last("limit 1")
        );
        if (appUser != null) {
            appUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            appUser.setLoginDate(LocalDateTime.now());
            appUserMapper.updateById(appUser);

            return appUser;
        }

        appUser = new AppUser();
        appUser.setUserName(userName);
        appUser.setMobile(userName);
        appUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        appUser.setLoginDate(LocalDateTime.now());
        appUserMapper.insert(appUser);

        return appUser;
    }

    /**
     * 密码校验
     *
     * @param password 明文
     * @param salt     盐
     * @param hashPwd  密文
     * @return boolean
     */
    @Override
    public boolean checkPassword(String password, String salt, String hashPwd) {

        return hashPwd.equals(DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }

    /**
     * 随即生成盐
     * 8位随机数
     *
     * @return salt 盐
     */
    private String generateSalt() {

        return RandomStringUtils.randomAlphanumeric(8);
    }

    public static void main(String[] args) {

        AppUserServiceImpl appUserService = new AppUserServiceImpl();
        String password = "123456";
        String salt = appUserService.generateSalt();
        System.out.printf("明文密码：%s%n", password);
        System.out.printf("盐：%s%n", salt);
        System.out.printf("密文密码：%s%n", DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }
}
